package com.jpm.transmaker
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.getQualifiedClassName;
	import flash.events.IOErrorEvent;
	import com.adobe.images.PNGEncoder;
	import flash.utils.ByteArray;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	
	/**
	 * ...
	 * @author Jonboy
	 */
	public class Main extends Sprite
	{
		private var assets:File = File.desktopDirectory.resolvePath("assets");
		
		public function Main():void
		{
			if (stage)
				init();
			else
				addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			workOn(assets);
		}
		
		private function workOn(directory:File):void
		{
			var dir:Array = directory.getDirectoryListing();
			
			for each (var file:File in dir)
			{
				if (file.isDirectory)
				{
					workOn(file);
				}
				else
				{
					var loader:Loader = new Loader();
					loader.contentLoaderInfo.addEventListener(Event.COMPLETE, ldrDone);
					loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ldrError);
					loader.load(new URLRequest(file.url));
				}
				
			}
		
		}
		
		private function ldrDone(event:Event):void
		{
			var srcBitmap:Bitmap = event.target.content;
			var dstBitmapData:BitmapData = new BitmapData(srcBitmap.width, srcBitmap.height, true);
			dstBitmapData.threshold(srcBitmap.bitmapData, new Rectangle(0, 0, srcBitmap.width, srcBitmap.height), new Point(0, 0), "==", 0xFFFF00FF, 0x00000000, 0x00FFFFFF, true);
			//addChild(new Bitmap(dstBitmapData));
			var byteArray:ByteArray = PNGEncoder.encode(dstBitmapData);
			var assetsout:File = new File(event.target.url.replace("assets", "assetsout"));
			var fs:FileStream = new FileStream();
			
			try
			{
				fs.open(assetsout, FileMode.WRITE);
				fs.writeBytes(byteArray);
				fs.close();
				trace(assetsout.name);
			}
			catch (e:Error)
			{
				trace(e.message);
			}
		
		}
		
		private function ldrError(event:Event):void
		{
			trace("Failed to load " + event.target.content);
		}
	}
}